package top.hymsk.ecommerce.dao.elasticsearch;


import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.hymsk.ecommerce.config.ElasticSearchConfig;

/**
 * @author 花于陌上开
 */
@Component
public class ESConnection {
    RestClientBuilder restHighLevelClientBuilder;

    public static Integer MAX_RESULT_NUMBER;
    public static Integer PAGE_SIZE;

    public ESConnection(@Autowired ElasticSearchConfig elasticSearchConfig) {
        ESConnection.MAX_RESULT_NUMBER = elasticSearchConfig.getMaxResultNumber();
        ESConnection.PAGE_SIZE = elasticSearchConfig.getPageSize();
        restHighLevelClientBuilder = RestClient.builder(HttpHost.create(elasticSearchConfig.getHttpHost())).setRequestConfigCallback(builder -> {
            return builder.setConnectTimeout(5000 * 1000) // 连接超时（默认为1秒）
                    .setSocketTimeout(6000 * 1000);// 套接字超时（默认为30秒）//更改客户端的超时限制默认30秒现在改为100分钟
        });
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticSearchConfig.getUsername(), elasticSearchConfig.getPassword()));
        restHighLevelClientBuilder.setHttpClientConfigCallback((HttpAsyncClientBuilder httpAsyncClientBuilder) -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
    }

    public RestHighLevelClient getClient() {
        return new RestHighLevelClient(restHighLevelClientBuilder);
    }
}
